package com.test.ssm.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 徒有琴
 */
@ServerEndpoint("/chat/{name}")
@Component
public class ChactController {
    //用昵称当key，把所有的session缓存起来
    private static Map<String, Session> allClients = new ConcurrentHashMap();//用于记录所有的用户和连接之间的关系

    @OnOpen//此注解的作用是声明当前方法是当建立连接的时候调用
    public void onOpen(@PathParam("name") String name, Session session) throws Exception {
        allClients.put(name, session);//将当前连接放入到 map中
    }

    @OnMessage//此注解的作用是当收到消息的时候执行
    public void onMessage(Session session, String message) {
        System.out.println("收到消息：" + message);
        ObjectMapper mapper = new ObjectMapper();
        //mapper.getDeserializationConfig().with(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        try {
            Map<String, Object> map = mapper.readValue(message, HashMap.class);
            String other = map.get("other").toString();
            String content = map.get("content").toString();
            Session otherSession = allClients.get(other);
            if (otherSession != null) {
                otherSession.getAsyncRemote().sendText(content);
            }else{
                session.getAsyncRemote().sendText("对方不在线");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //向客户端返回消息
        //session.getAsyncRemote().sendText("我收到了，你发的是：" + message);
    }

    public static void  send(String orderNum,String message){
        Session otherSession = allClients.get(orderNum);
        if (otherSession != null) {
            otherSession.getAsyncRemote().sendText(message);
        }
    }
}
